package com.flute.haflute.jobbox.common;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;

import com.flute.haflute.client.TransferredFiles;
import com.flute.haflute.jobbox.communication.messages.FileTransferMessage;

public class TransferredFileWriter {
	public void writeContentFromMessage(FileTransferMessage message) throws RemoteException {
		TransferredFiles fileContents = message.getContent();
		for(int i=0; i<fileContents.getFileNames().size(); i++) {
			String fileName = fileContents.getFileNames().get(i);
			byte[] content = fileContents.getFileContents().get(i);
			write2File(fileName,content);	
		}
	}

	private void write2File(String fileName, byte[] content) throws RemoteException {
		File newFile = new File(fileName);
		String filePath = newFile.getAbsolutePath();
		String dirPath = filePath.substring(0,filePath.lastIndexOf(File.separator));
		File dir = new File(dirPath);
		if(!dir.exists()) {
			if(!dir.mkdirs()) {
				throw new RemoteException("can not make all dirs: " + dir.getAbsolutePath());
			}
		}
		BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(newFile));
			bos.write(content);
			bos.close();
		} catch (IOException e) {
			RemoteException re = new RemoteException();
			re.setStackTrace(e.getStackTrace());
			throw re;
		}
	}

}
